(function(){

  angular.module('object',['ng.ueditor'])
        .controller('ObjectController', [
          '$scope', '$stateParams', 'API', 'LxNotificationService', 'LxDialogService','$upload', ObjectController
        ])
        .filter('isChecked', function() {
          return function(input) {
            return input==1 ? "checked" : "";
          };
        });;

  /**
   * Main Controller for the Angular Material Starter App
   */
  function ObjectController( $scope, $stateParams, API, LxNotificationService, LxDialogService,$upload) {
    var objectName = $stateParams.objectName;
    var pageNumNow = 1;
    var perPageNow = 10;
    var objectNow = {};

    $scope.orderField = null;
    $scope.orderValue = null

    //配置项
    API.get({"object":objectName,"id":"config"},function(returnData){
      if(!returnData.error){

        $scope.objectConfig = returnData.result;
        console.log("配置项",$scope.objectConfig);
        $scope.index(pageNumNow,perPageNow);
      }
    });

    //分页
    $scope.perPages = [{num:'5'},{num:'10'},{num:'20'},{num:'30'},{num:'50'}]; 
    $scope.perPage = $scope.perPages[1].num;    
    function getPager(total){
      var pager = [];
      pager['currentPage'] = total.currentPage *1;
      pager['lastPage'] = total.lastPage==0?1:total.lastPage;
      pager['pages']  = [];
      for (var i = 1; i < total.last_page+1; i++) {
         pager['pages'].push(i);
      };
      return pager;
    }

    //搜索
    $scope.filter = function(){
      $scope.object = {};

      angular.forEach($scope.objectConfig.fields,function(field){
        if(field.type == "textarea") field.default = null;
        if(field.type == "timestamp") field.default = null;
        if(field.type == "text") field.default = null;
        if(field.type == "varchar")  field.default = null;
        if(field.type == "int")  field.default = null;
        if(field.type == "boolean") field.default = false;
        if(field.default != null)
        $scope.object[field.name] = field.default;         
      });
      LxDialogService.open('filterDialog');
    };
    
    $scope.order = function(field){ 

      if(!field.is_order) return;

      $scope.orderField = field.name;
      $scope.orderValue = field.orderValue?false:true;
      field.orderValue = $scope.orderValue;
      $scope.index(pageNumNow,perPageNow);
    }; 

    //索引
    $scope.index = function(pageNum,perPage,object){

      pageNum = pageNum?pageNum:pageNumNow;
      pageNumNow = pageNum;   

      perPage  = perPage ?perPage :perPageNow;
      perPageNow = perPage ;

      object  = object ?object :objectNow;
      objectNow = object ; 
   
      if (object.is_delete === true || object.is_delete === false ) {
        object.is_delete = object.is_delete == true?1:0;
      };
      console.log(object);
      var filterOption={};i=0;
      angular.forEach(object,function(value,key){
        filterOption["filter["+i+"][0]"] = key; 
        filterOption["filter["+i+"][1]"] = "LIKE"; 
        filterOption["filter["+i+"][2]"] = value; 
        i++;    
      });


      filterOption["object"] = objectName;
      filterOption["currentPage"] = pageNum;
      filterOption["countPerPage"] = perPage;
      filterOption["field"] = $scope.orderField;
      filterOption["order"] = $scope.orderValue;
      console.log("查找条件",filterOption);

      API.query(filterOption,function(returnData){
        if(!returnData.error){
          $scope.pager = getPager(returnData.result);
          $scope.objects = returnData.result.data;
          console.log("详情",$scope.objects);
        }
      }); 
    }

    //单条记录
    $scope.show = function(object){
      if(object){
        API.get({"object":objectName,"id":object.id},function(returnData){
          if(!returnData.error){
            console.log("单条记录",returnData.result);
            returnData.result.is_delete = returnData.result.is_delete==0?false:true;
            $scope.object = returnData.result;
          }
        });  
      }else{
        $scope.object = {};
        angular.forEach($scope.objectConfig.fields,function(field){
          if(field.type == "date" || "timestamp") field.default = null;
          if(field.name == "created_by") field.default = "1";
          if(field.default != null)
            $scope.object[field.name] = field.default;
        });
      }

      LxDialogService.open('showDialog');
    }

    //创建或更新
    $scope.store = function(object){
      console.log("提交内容",object);
      if(object.id){
        console.log(object);
        API.update({"object":objectName,"id":object.id},object,function(returnData){
          if(!returnData.error){
            console.log("更新结果",returnData.result.data);
            LxNotificationService.success('更新成功！');
            LxDialogService.close('showDialog');
          }else{
            LxNotificationService.error('更新失败！');
          }
          $scope.index();
        }); 

      }else{

        var fitlerArr = [];
        for (var i = object.length - 1; i >= 0; i--) {
          var filterField = object[i];
        };

        API.save({"object":objectName},object,function(returnData){
          if(!returnData.error){
            console.log("创建结果",returnData.result.data);
            LxNotificationService.success('创建成功！！');
            LxDialogService.close('showDialog');
          }else{
            LxNotificationService.error('创建失败！');
          }
          $scope.index();
        });

      }

    };

    //删除
    $scope.destroy = function(object){

      LxNotificationService.confirm('确定删除此记录？', '删除后不可恢复！', { cancel:'取消', ok:'删除' }, function(answer)
      {
        if(!answer) return false;
      
        API.delete({"object":objectName,"id":object.id},function(returnData){
          if(!returnData.error){
            console.log("删除结果",returnData.result.data);
            $scope.objects.splice($scope.objects.indexOf(object), 1);
            LxNotificationService.success('删除成功！');
          }else{
            LxNotificationService.error('删除失败！');
          }
        });

      });

    };


    //上传文件
    $scope.$watch('files', function () {
        $scope.upload($scope.files);
    });
    $scope.upload = function (files,object) {
        if (files && files.length) {
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                $upload.upload({
                    url: '/file',
                    fields: {'id': '123'},
                    file: file,
                    data: file,
                    method: 'post',
                    fileFormDataName:"file",
                    headers: {'Content-Type': file.type}
                }).progress(function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
                }).success(function (data, status, headers, config) {
                  // console.log(data);
                  object.img_dir = data.result;
                });
            }
        }
    };


    //ajax关联项
    $scope.ajax = {
        selected: '',
        list: [],
        update: function(relate, newFilter, oldFilter)
        {
            if (newFilter)
            {
                $scope.ajax.loading = true;
                var relateTable  = relate.table;
                var relateSelect = relate.select;
                var filterStr = (relate.filter?relate.filter + " AND ":"") + relateTable + "." + relateSelect + " LIKE '%" + newFilter + "%'";

                API.query({"object":relateTable,"filter_str":filterStr,"no_relate":1},function(returnData){
                  if(!returnData.error){
                    console.log("关联查找结果",relateTable,returnData.result.data);
                    $scope.ajax.list = returnData.result.data;
                    $scope.ajax.loading = false;

                  }else{
                    $scope.ajax.loading = false;
                  }
                },function(){
                    $scope.ajax.loading = false;
                });
            }
            else
            {
                $scope.ajax.list = false;
            }
        },
        toModel: function(relate, data, callback)
        {
            if (data)
            {
                callback(data[relate.field]);
            }
            else
            {
                callback();
            }
        },
        toSelection: function(relate, data, callback)
        {
            if (data)
            {
                var relateTable  = relate.table;
                var relateFiled = relate.field;
                var filterStr = (relate.filter?relate.filter + " AND ":"") + relateTable + "." + relateFiled + " = '" + data+"'";

                API.query({"object":relateTable,"filter_str":filterStr,"no_relate":1},function(returnData){
                  if(!returnData.error){
                    console.log("关联查找结果",relateTable,returnData.result.data);
                    callback(returnData.result.data[0]);
                  }else{
                    callback();
                  }
                },function(){
                   callback();
                });
            }
            else
            {
                callback();
            }
        },
        loading: false
    };

  }
  

})();
